﻿using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using Control = CastingWellEquipmentGUI.Model.Control;

namespace CastingWellEquipmentGUI.Config
{
    public static class SystemConfig
    {
        /// <summary>
        /// 系统配置xml文件地址
        /// </summary>
        public static string xmlFilePath = System.Windows.Forms.Application.StartupPath + "\\applicationConfig.xml";
        /// <summary>
        /// 数据库IP地址
        /// </summary>
        public static string dataBaseIpAddress;
        /// <summary>
        /// 设备类别
        /// </summary>
        public static string equipmentCategory;
        /// <summary>
        /// 上一页
        /// </summary>
        public static string prevPage;
        /// <summary>
        /// 系统状态
        /// </summary>
        public static string systemState;
        /// <summary>
        /// 系统运行状态
        /// </summary>
        public static string SystemStatus;
        /// <summary>
        /// 被编辑的配方实体类
        /// </summary>
        public static RecipeTableByVerification _EditModel = new RecipeTableByVerification();

        /// <summary>
        /// 铸造编号
        /// </summary>
        private static string CastingNo;
        /// <summary>
        /// 设置铸造编号
        /// </summary>
        /// <param name="CastingNo"></param>
        public static void SetCastingNo(string CastingNo)
        {
            SystemConfig.CastingNo = CastingNo;
            CastNumberTable castNumberTable = new CastNumberTable
            {
                CastNumber = CastingNo
            };
            string sql = @"INSERT INTO CastNumberTable
                                       (CastNumber
                                       ,CastStartTime
                                       ,CastStopTime
                                       ,RepiceName
                                       ,RecipeId
                                       ,RepiceRevName)
                           VALUES (
                                   @CastNumber,
                                   null,
                                   null,
                                   null,
                                   null,
                                   null
                                   )";
            int resultCount = DapperToolsThisSystem.Add<CastNumberTable>(sql, castNumberTable);
            if (resultCount == 0)
            {
                throw new Exception();
            }
        }

        /// <summary>
        /// 获取铸造编号
        /// </summary>
        public static string GetCastingNo()
        {
            CastNumberTable castNumberTable = new CastNumberTable();
            string sql = @"SELECT TOP 1 * FROM CastNumberTable WHERE CastStopTime IS NULL ORDER BY CastId DESC";
            CastNumberTable dataBaseCastNumber = DapperToolsThisSystem.Query<CastNumberTable>(sql, castNumberTable);
            if (SystemConfig.CastingNo != null)
            {
                if (SystemConfig.CastingNo == dataBaseCastNumber.CastNumber)
                {
                    return SystemConfig.CastingNo;
                }
                else
                {
                    SystemConfig.CastingNo = dataBaseCastNumber.CastNumber;
                    return SystemConfig.CastingNo;
                }
            }
            else
            {
                SystemConfig.CastingNo = dataBaseCastNumber.CastNumber;
                return SystemConfig.CastingNo;
            }
        }

        /// <summary>
        /// 根据 窗体名，窗体TAG值和窗体对象补全窗体，控件和权限数据
        /// </summary>
        /// <param name="FormName"></param>
        /// <param name="PermissionsName"></param>
        /// <param name="parent"></param>
        public static void AnalysisFormControlStructureGenerationPermission(string FormName, string PermissionsName, DependencyObject parent)
        {
            string QueryFromSql = "SELECT * FROM Form WHERE FormName = @FormName";
            Model.Form whereForm = new Model.Form
            {
                FormName = FormName,
                FormExplain = PermissionsName
            };
            Model.Form dataBaseForm = DapperToolsThisSystem.Query(QueryFromSql, whereForm);
            if (dataBaseForm == null)
            {
                string AddFromSql = "INSERT INTO Form(FormName,FormExplain) VALUES(@FormName,@FormExplain)";
                DapperToolsThisSystem.Add(AddFromSql, whereForm);
                dataBaseForm = DapperToolsThisSystem.Query(QueryFromSql, whereForm);
            }
            List<System.Windows.Controls.Control> controls = new List<System.Windows.Controls.Control>();
            FindVisualChild(parent, ref controls);
            for (int i = 0; i < controls.Count; i++)
            {
                if (controls[i].Name == "PART_ContentHost")
                {
                    continue;
                }
                if (controls[i].Name != "" && controls[i].Tag != null && controls[i].Tag.ToString() != "")
                {
                    string QueryControlSql = "SELECT * FROM Control WHERE ControlName = @ControlName AND FormId = @FormId";
                    Model.Control whereControl = new Model.Control
                    {
                        ControlName = controls[i].Name,
                        FormId = dataBaseForm.FormId,
                        ControlExplain = controls[i].Tag.ToString()
                    };
                    Model.Control dataBaseControl = DapperToolsThisSystem.Query(QueryControlSql, whereControl);
                    if (dataBaseControl == null)
                    {
                        string AddControlSql = "INSERT INTO Control(ControlName,ControlType,FormId,ControlExplain) VALUES(@ControlName,1,@FormId,@ControlExplain)";
                        DapperToolsThisSystem.Add(AddControlSql, whereControl);
                        dataBaseControl = DapperToolsThisSystem.Query(QueryControlSql, whereControl);
                    }
                    string QueryPermissionsSql = "SELECT * FROM Permissions WHERE FormId = @FormId AND ControlId = @ControlId";
                    Model.Permissions wherePermissions = new Model.Permissions
                    {
                        FormId = dataBaseForm.FormId,
                        ControlId = dataBaseControl.ControlId
                    };
                    Model.Permissions dataBasePermissions = DapperToolsThisSystem.Query(QueryPermissionsSql, wherePermissions);
                    if (dataBasePermissions == null)
                    {
                        wherePermissions.PermissionsName = PermissionsName + "->" + controls[i].Tag;
                        string AddPermissions = "INSERT INTO Permissions(PermissionsName,FormId,ControlId) VALUES(@PermissionsName,@FormId,@ControlId)";
                        DapperToolsThisSystem.Add(AddPermissions, wherePermissions);
                    }
                }
            }

            for (int k = 0; k < LogTool.CurrentUser.Roles.Count; k++)
            {
                Role role = LogTool.CurrentUser.Roles[k];
                string findWherePermissionsAndRoleSql = @"SELECT 
                                                                b.*
                                                          FROM PermissionsAndRole a
                                                          FULL JOIN Permissions b ON a.PermissionsId = b.PermissionsId
                                                          FULL JOIN Role c ON a.RoleId = c.RoleId
                                                          WHERE ((a.PermissionsId IS NULL AND b.PermissionsId IS NOT NULL) 
                                                          OR  (a.RoleId IS NULL AND c.RoleId IS NOT NULL AND c.RoleId = " + role.RoleId + "))";
                List<Permissions> NotHavePermissions = DapperToolsThisSystem.Query<Permissions>(findWherePermissionsAndRoleSql);
                for (int j = 0; j < NotHavePermissions.Count; j++)
                {
                    PermissionsAndRole permissionsAndRole = new PermissionsAndRole
                    {
                        PermissionsId = NotHavePermissions[j].PermissionsId,
                        RoleId = role.RoleId
                    };
                    if (role.RoleName == "管理员")
                    {
                        permissionsAndRole.IsShow = true;
                        permissionsAndRole.IsEnable = true;
                    }
                    else
                    {
                        permissionsAndRole.IsShow = false;
                        permissionsAndRole.IsEnable = false;
                    }
                    string AddPermissionsAndRoleSql = "INSERT INTO PermissionsAndRole (PermissionsId,RoleId,IsShow,IsEnable) VALUES(@PermissionsId,@RoleId,@IsShow,@IsEnable)";
                    DapperToolsThisSystem.Add(AddPermissionsAndRoleSql, permissionsAndRole);
                }
            }
        }


        /// <summary>
        /// 查找子控件
        /// </summary>
        /// <typeparam name="T">控件类型</typeparam>
        /// <param name="parent">父控件依赖对象</param>
        /// <param name="lstT">子控件列表</param>
        public static void FindVisualChild<T>(DependencyObject parent, ref List<T> lstT) where T : DependencyObject
        {
            if (parent != null)
            {
                T child = default(T);
                int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < numVisuals; i++)
                {
                    Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                    child = v as T;
                    if (child != null)
                    {
                        lstT.Add(child);
                    }
                    FindVisualChild<T>(v, ref lstT);
                }
            }
        }


        public static int QueryTagIdByControlNameAndFormName(string FormName, string ControlName)
        {

            Control controlWhere = new Control();
            controlWhere.FormName = FormName;
            controlWhere.ControlName = ControlName;
            Control control = DapperToolsThisSystem.Query(@"SELECT 
                                                            a.*
                                                            FROM DB_CWEGUI.dbo.Control a
                                                            LEFT JOIN DB_CWEGUI.dbo.Form b ON a.FormId = b.FormId
                                                            WHERE b.FormName = @FormName
                                                            AND a.ControlName = @ControlName", controlWhere);
            int TagId = 0;
            ControlTag controTagWhere = new ControlTag();
            controTagWhere.ControlId = control.ControlId;
            ControlTag controlTag = DapperToolsThisSystem.Query(@"SELECT
                                                                   a.*
                                                                  FROM DB_CWEGUI.dbo.ControlAndTagInfo a
                                                                  WHERE a.ControlId = @ControlId", controTagWhere);
            if (controlTag != null)
            {
                TagId = controlTag.TagID;
            }
            return TagId;
        }


    }
}
